/*
 * @Author: Bing
 * @Date: 2024-02-08 17:14:25
 * @LastEditors: Bing
 * @LastEditTime: 2024-02-11 23:52:07
 * @Description: file content
 * @FilePath: \mi365plus\src\utils\http.ts
 */
import jsonBigInt from 'json-bigint';
import { useMemberStore } from '@/stores/modules/member';
import { requestInterceptor, responseInterceptor } from './interceptor';

// 拦截 request 请求
uni.addInterceptor('request', requestInterceptor);
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', requestInterceptor);

// 响应拦截response 请求
uni.addInterceptor('response', responseInterceptor);
const BASE_URL = 'https://cf.emucoo.net/V1.1';
/**
 * 响应格式
 */
export type Data<T> = {
  code: string;
  data: T;
  msg: string;
  pageNumber: number;
  pages: number;
  pageSize: number;
  total: number;
  version: number;
};
/**
 * 请求封装
 */
export const http = <T>(options: UniApp.RequestOptions) => {
  // 1. 返回 Promise 对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // #ifdef H5
      url: options.url,
      // #endif
      // #ifndef H5
      url: BASE_URL + options.url,
      // #endif
      method: options.method,
      dataType: 'string',
      data: {
        data: options.data,
        pageNumber: 1,
        pageSize: 30,
        sign: 'fake sign',
      },
      header: {
        ...options.header,
        'Content-Type': 'application/json',
      },
      // 响应成功
      success(res) {
        const JSONstrict = jsonBigInt({ storeAsString: true });
        res.data = JSONstrict.parse(res.data as any);
        // 状态码 2xx，参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if ((res.data as Data<T>).msg === 'success') {
            resolve(res.data as Data<T>);
            return;
          } else if ((res.data as Data<T>).code === '401') {
            uni.showToast({ title: (res.data as Data<T>).msg, icon: 'error' });
            useMemberStore().clearProfile();
            setTimeout(() => {
              uni.switchTab({ url: '/pages/mySetting/mySetting' });
            }, 500);
            resolve(res.data as Data<T>);
            return;
          } else if ((res.data as Data<T>).msg === '未经授权') {
            console.log('未授权');
            uni.showToast({
              icon: 'error',
              title: '未经授权',
            });
            return;
          } else {
            // 退出登录
            useMemberStore().clearProfile();
            uni.showToast({
              icon: 'none',
              title: (res.data as Data<T>).msg || '请求错误',
            });
            resolve(res.data as Data<T>);
          }
        } else if (res.statusCode === 401) {
          // 401 跳转到登录页,且退出登录
          reject(res);
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).msg || '请求错误',
          });
          reject(res);
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
        });
        reject(err);
      },
    });
  });
};

/**
 * 图片响应格式
 */
export type ImgResponse = {
  bucket: string;
  fsize: number;
  hash: string;
  key: string;
  url: string;
};
/**
 * 图片上传请求封装
 * @param filePaths 路径
 */
export const uploadImg = (filePaths: UniHelper.PickerInstance) => {
  const { tempFilePaths } = filePaths;
  return new Promise<ImgResponse>((resolve, reject) => {
    uni.uploadFile({
      url: 'https://upload-z2.qiniup.com/', //上传图片的后端接口
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        token: useMemberStore().getProfile()?.imgToken,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          uni.showToast({ title: '图片上传成功', icon: 'none' });
          resolve(JSON.parse(res.data) as ImgResponse);
        }
      },
      fail: (err) => {
        uni.showToast({ title: err.errMsg, icon: 'error' });
        reject(err);
      },
    });
  });
};
